import {reqCartList,reqDeleteCart,reqUpdateCheckById} from '@/api';
const state = {
    cartList:[]
}
const mutations = {
    GETCARTLIST(state,cartList){
        state.cartList = cartList
    }
}
const actions = {
    // 获取购物车列表数据
    async getCartList({commit}){
        const res = await reqCartList()
        if(res.code == 200){
            commit('GETCARTLIST',res.data)
        }
    },
    // 删除购物车某个产品
    async deleteCartListBySkuId({commit},skuId){
        const res = await reqDeleteCart(skuId)
        if(res.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 修改购物车选中状态
    async updateChangeById({commit},{skuId,isChecked}){
        const res = await reqUpdateCheckById(skuId,isChecked)
        if(res.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 删除全部勾选的产品
    deleteAllCheckedCart({dispatch,getters}){
        // 获取购物车中全部的产品
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            if(item.isChecked == 1){
                let res = dispatch('deleteCartListBySkuId',item.skuId)
                // 将每一次返回的Promise添加到数组中
                PromiseAll.push(res)
            }
        });
        // 只要全部的 promise 都成功，返回结果为 成功
        return Promise.all(PromiseAll)
    },
    // 修改全部产品选中状态啊
    updateAllCartIsChecked({dispatch,state},isChecked){
        let promiseAll = []
        state.cartList[0].cartInfoList.forEach(item=>{
            let promise =  dispatch('updateChangeById',{skuId:item.skuId,isChecked})
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }

}
const getters = {
    cartList(state){
        return state.cartList[0] || {}
    }
}
export default {
    state,
    actions,
    mutations,
    getters
}